<template>
  <view class="container">
    <view class="header">
      <text class="title">我的闹钟</text>
      <view class="add-btn" @click="goToAddAlarm">
        <text class="add-icon">+</text>
      </view>
    </view>

    <!-- 闹钟列表 -->
    <view class="alarm-list" v-if="alarms.length > 0">
      <view
        v-for="alarm in alarms"
        :key="alarm.id"
        class="alarm-item"
        :class="{ disabled: !alarm.isActive }"
      >
        <view class="alarm-info">
          <text class="alarm-time">{{ alarm.time }}</text>
          <text class="alarm-label">{{ alarm.label }}</text>
          <!-- 一次性闹钟显示日期 -->
          <view class="alarm-date" v-if="alarm.type === 'once' && alarm.date">
            <text class="date-label">📅 {{ formatDate(alarm.date) }}</text>
          </view>
          <!-- 重复闹钟显示星期 -->
          <view
            class="alarm-repeat"
            v-if="
              alarm.type === 'repeat' &&
              alarm.repeatDays &&
              alarm.repeatDays.length > 0
            "
          >
            <text
              v-for="dayIndex in alarm.repeatDays"
              :key="dayIndex"
              class="repeat-day"
            >
              {{ weekDays[dayIndex] }}
            </text>
          </view>
          <!-- 兼容旧版本数据（没有type字段的旧闹钟） -->
          <view
            class="alarm-repeat"
            v-if="
              !alarm.type && alarm.repeatDays && alarm.repeatDays.length > 0
            "
          >
            <text
              v-for="dayIndex in alarm.repeatDays"
              :key="dayIndex"
              class="repeat-day"
            >
              {{ weekDays[dayIndex] }}
            </text>
          </view>
        </view>

        <view class="alarm-actions">
          <switch
            :checked="alarm.isActive"
            @change="toggleAlarm(alarm.id)"
            color="#007AFF"
          />
          <view class="delete-btn" @click="deleteAlarm(alarm.id)">
            <text class="delete-icon">×</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <view class="empty-icon">⏰</view>
      <text class="empty-text">还没有设置闹钟</text>
      <text class="empty-desc">点击右上角 + 号添加你的第一个闹钟</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      alarms: [],
      weekDays: ["日", "一", "二", "三", "四", "五", "六"],
      checkTimer: null,
      vibrationTimer: null,
      vibrationCount: 0,
      isAppActive: true,
    };
  },
  onShow() {
    this.isAppActive = true;
    this.loadAlarms();
    this.startAlarmCheck();
    this.requestBackgroundPermission();
  },
  onHide() {
    this.isAppActive = false;
    // 不停止闹钟检查，保持后台运行
    console.log("应用进入后台，闹钟检查继续运行");
  },
  onUnload() {
    this.stopAlarmCheck();
    this.stopVibration();
  },
  methods: {
    loadAlarms() {
      try {
        const alarms = uni.getStorageSync("alarms") || [];
        this.alarms = alarms.sort((a, b) => {
          // 按时间排序
          return a.time.localeCompare(b.time);
        });
      } catch (error) {
        console.error("加载闹钟失败:", error);
        this.alarms = [];
      }
    },
    async toggleAlarm(alarmId) {
      try {
        const alarms = uni.getStorageSync("alarms") || [];
        const updatedAlarms = alarms.map((alarm) => {
          if (alarm.id === alarmId) {
            return { ...alarm, isActive: !alarm.isActive };
          }
          return alarm;
        });

        uni.setStorageSync("alarms", updatedAlarms);
        this.loadAlarms();

        const alarm = updatedAlarms.find((a) => a.id === alarmId);
        uni.showToast({
          title: alarm.isActive ? "闹钟已开启" : "闹钟已关闭",
          icon: "none",
        });
      } catch (error) {
        uni.showToast({
          title: "操作失败",
          icon: "none",
        });
      }
    },
    deleteAlarm(alarmId) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这个闹钟吗？",
        success: (res) => {
          if (res.confirm) {
            try {
              const alarms = uni.getStorageSync("alarms") || [];
              const filteredAlarms = alarms.filter(
                (alarm) => alarm.id !== alarmId
              );
              uni.setStorageSync("alarms", filteredAlarms);
              this.loadAlarms();

              uni.showToast({
                title: "闹钟已删除",
                icon: "success",
              });
            } catch (error) {
              uni.showToast({
                title: "删除失败",
                icon: "none",
              });
            }
          }
        },
      });
    },
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}/${month}/${day}`;
    },
    goToAddAlarm() {
      uni.navigateTo({ url: "/pages/add-alarm/add-alarm" });
    },
    startAlarmCheck() {
      // 清除之前的定时器
      if (this.checkTimer) {
        clearInterval(this.checkTimer);
      }

      // 启动新的定时器，每秒检查一次
      this.checkTimer = setInterval(() => {
        this.checkAlarms();
      }, 1000);

      console.log("闹钟检查已启动");
    },
    stopAlarmCheck() {
      if (this.checkTimer) {
        clearInterval(this.checkTimer);
        this.checkTimer = null;
      }
    },
    checkAlarms() {
      const now = new Date();
      const currentTime = `${String(now.getHours()).padStart(2, "0")}:${String(
        now.getMinutes()
      ).padStart(2, "0")}`;
      const currentDay = now.getDay();
      const currentDate = now.toISOString().split("T")[0]; // YYYY-MM-DD 格式

      this.alarms.forEach((alarm) => {
        if (alarm.isActive && alarm.time === currentTime) {
          if (alarm.type === "once") {
            // 一次性闹钟：检查日期是否匹配
            if (alarm.date === currentDate) {
              this.triggerAlarm(alarm);
              // 关闭一次性闹钟
              this.toggleAlarm(alarm.id);
            }
          } else if (alarm.type === "repeat") {
            // 重复闹钟：检查星期是否匹配
            if (alarm.repeatDays && alarm.repeatDays.includes(currentDay)) {
              this.triggerAlarm(alarm);
            }
          } else {
            // 兼容旧版本数据（没有type字段）
            if (alarm.repeatDays && alarm.repeatDays.length > 0) {
              if (alarm.repeatDays.includes(currentDay)) {
                this.triggerAlarm(alarm);
              }
            } else {
              // 旧版本一次性闹钟
              this.triggerAlarm(alarm);
              this.toggleAlarm(alarm.id);
            }
          }
        }
      });
    },
    triggerAlarm(alarm) {
      console.log("闹钟触发:", alarm);

      // 强化振动效果
      if (alarm.vibrate) {
        // 连续振动多次以确保用户感知
        this.performVibration();
      }

      // 显示闹钟提醒
      uni.showModal({
        title: "⏰ 闹钟提醒",
        content: `${alarm.time} - ${alarm.label}`,
        confirmText: "知道了",
        showCancel: false,
        success: () => {
          console.log("闹钟提醒已确认");
          // 停止振动
          this.stopVibration();
        },
      });

      // 发送系统通知和播放提示音
      // #ifdef APP-PLUS
      try {
        // 创建本地通知
        plus.push.createMessage(`${alarm.time} - ${alarm.label}`, "", {
          title: "⏰ 闹钟提醒",
          when: new Date(),
          cover: false,
        });

        // 播放系统提示音
        plus.device.beep(3);

        // 唤醒屏幕
        plus.device.wakelock();
      } catch (error) {
        console.error("创建通知或播放提示音失败:", error);
      }
      // #endif
    },

    performVibration() {
      // 立即振动一次 - 使用官方API
      uni.vibrate({
        success: () => {
          console.log("震动成功");
        },
        fail: (err) => {
          console.error("震动失败:", err);
        },
      });

      // 连续振动模式
      this.vibrationCount = 0;
      this.vibrationTimer = setInterval(() => {
        if (this.vibrationCount < 15) {
          // 振动15次
          uni.vibrate({
            success: () => {
              console.log(`第${this.vibrationCount + 1}次震动成功`);
            },
            fail: (err) => {
              console.error(`第${this.vibrationCount + 1}次震动失败:`, err);
            },
          });
          this.vibrationCount++;
        } else {
          this.stopVibration();
        }
      }, 800); // 每0.8秒振动一次
    },

    stopVibration() {
      if (this.vibrationTimer) {
        clearInterval(this.vibrationTimer);
        this.vibrationTimer = null;
      }
    },

    requestBackgroundPermission() {
      // #ifdef APP-PLUS
      try {
        // 请求忽略电池优化权限
        const main = plus.android.runtimeMainActivity();
        const Intent = plus.android.importClass("android.content.Intent");
        const Settings = plus.android.importClass("android.provider.Settings");

        const intent = new Intent(
          Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
        );
        intent.setData(
          plus.android.newObject(
            "android.net.Uri",
            "package:" + main.getPackageName()
          )
        );
        main.startActivity(intent);

        console.log("已请求电池优化权限");
      } catch (error) {
        console.error("请求后台权限失败:", error);
      }
      // #endif
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f6f8fb;
  padding: 30rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
}

.add-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-icon {
  color: #fff;
  font-size: 40rpx;
  font-weight: 300;
}

.alarm-list {
  space-y: 20rpx;
}

.alarm-item {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.alarm-item.disabled {
  opacity: 0.5;
}

.alarm-info {
  flex: 1;
}

.alarm-time {
  display: block;
  font-size: 48rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
}

.alarm-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.alarm-date {
  margin-top: 10rpx;
}

.date-label {
  font-size: 24rpx;
  color: #007aff;
  background-color: #e3f2fd;
  padding: 5rpx 12rpx;
  border-radius: 15rpx;
  display: inline-block;
}

.alarm-repeat {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.repeat-day {
  background-color: #e3f2fd;
  color: #1976d2;
  padding: 5rpx 12rpx;
  margin: 5rpx 10rpx 5rpx 0;
  border-radius: 15rpx;
  font-size: 24rpx;
}

.alarm-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.delete-btn {
  width: 50rpx;
  height: 50rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: #fff;
  font-size: 30rpx;
  font-weight: 300;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 36rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  line-height: 1.5;
}
</style>
